package com.zhupanlin.service;

import com.zhupanlin.dao.UserDao;
import com.zhupanlin.entity.Role;
import com.zhupanlin.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/12/17 23:24
 */
@Service
public class MyUserDetailService implements UserDetailsService, UserDetailsPasswordService {

    private final UserDao userDao;

    @Autowired
    public MyUserDetailService(UserDao userDao) {
        this.userDao = userDao;
    }

    /**
     * 更新密码策略 默认使用DelegatingPasswordEncoder 相对最安全密码加密 Bcrypt -->
     * @param user
     * @param newPassword
     * @return
     */
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer result = userDao.updatePassword(user.getUsername(), newPassword);
        if (result == 1) {
            ((User) user).setPassword(newPassword);
        }
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.loadUserByUsername(username);
        List<Role> roles = userDao.getRolesByUid(user.getId());
        user.setRoles(roles);


        return user;
    }
}
